package vip.aster.framework.config;

import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置文件加解密
 *
 * @author Aster
 * @since 2024/2/5 15:48
 */
@Configuration
@ConditionalOnProperty(prefix = "jasypt", name="enabled", havingValue = "true",matchIfMissing = false)
@EnableEncryptableProperties
public class JasyptConfiguration {

    @Value("${jasypt.password:aster}")
    private String jasyptPassword;

    @Bean("jasyptStringEncryptor")
    public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        // 这是加密的盐
        config.setPassword(jasyptPassword);
        // 加密算法
        config.setAlgorithm("PBEWithMD5AndDES");
        // 迭代次数
        config.setKeyObtentionIterations(1000);
        config.setPoolSize(1);
        // 提供方
        config.setProviderName("SunJCE");
        // 随机盐生成器
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }


    public static void main(String[] args) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        // 这是加密的盐, 此处需要改成你自己的盐
        config.setPassword("salt");
        // 加密算法
        config.setAlgorithm("PBEWithMD5AndDES");
        // 迭代次数
        config.setKeyObtentionIterations(1000);
        config.setPoolSize(1);
        // 提供方
        config.setProviderName("SunJCE");
        // 随机盐生成器
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");

        encryptor.setConfig(config);
        //加密, 这是你要加密的字符串
        String jasyptPasswordEN =encryptor.encrypt("aster");
        //解密
        String jasyptPasswordDE =encryptor.decrypt(jasyptPasswordEN);
        System.out.println("加密后密码："+jasyptPasswordEN);
        System.out.println("解密后密码："+jasyptPasswordDE);
    }

}
